/**
 * Created by ChenYong on 2017-04-12.
 *
 * 角色列表。
 */

$(function () {
    /** 角色名称的 jQuery 对象 */
    var $roleName = $("#role_name");
    /** 角色代码 jQuery 对象 */
    var $roleCode = $("#role_code");
    /** 开始日期的 jQuery 对象 */
    var $startDate = $("#start_date");
    /** 结束日期的 jQuery 对象 */
    var $endDate = $("#end_date");
    /** 清空开始日期的 jQuery 对象 */
    var $startDateCloseBtn = $("#start_date_close_btn");
    /** 清空结束日期的 jQuery 对象 */
    var $endDateCloseBtn = $("#end_date_close_btn");
    /** 搜索按钮的 jQuery 对象 */
    var $searchBtn = $("#search_btn");
    /** 角色模态框的 jQuery 对象 */
    var $roleModal = $("#role_modal");
    /** 角色列表的表格，DataTables 的 API 对象 */
    var roleTable = null;

    // 选择开始日期
    $startDate.datepicker({
        format: 'yyyy-mm-dd',
        language: "zh-CN",
        todayBtn: "linked",
        autoclose: true
    });

    // 选择结束日期
    $endDate.datepicker({
        format: 'yyyy-mm-dd',
        language: "zh-CN",
        todayBtn: "linked",
        autoclose: true
    });

    // 清空开始日期
    $startDateCloseBtn.click(function () {
        $startDate.val("");
    });

    // 清空结束日期
    $endDateCloseBtn.click(function () {
        $endDate.val("");
    });

    // 点击搜索按钮
    $searchBtn.click(function (e) {
        searchData();
    });

    // 监听角色模态框打开
    $roleModal.on("shown.bs.modal", function () {
        // 将滚动条滚动到顶部
        $roleModal.find(".modal-body").scrollTop("0px");
    });

    // 监听角色模态框关闭
    $roleModal.on("hidden.bs.modal", function () {
        $roleModal.find(".modal-body").html("");
    });

    // 点击删除角色
    $(document).on("click", ".delete_btn", function () {
        var $this = $(this);
        var id = $this.data("id");
        var name = $this.data("name");

        $.showConfirmModal({
            msg: "确定删除角色【{0}】吗？".format(name),
            confirmFn: function () {
                $.myAjax({
                    url: "web/role/delete.json",
                    modal: true,
                    data: {
                        id: id
                    },
                    successFn: function (data) {
                        searchData();
                    }
                });
            }
        });
    });

    // 展示角色表格
    roleTable = $("#role_table").myDataTable({
        url: "web/role/list.json",
        searchBtn: $searchBtn,
        sScrollY: "450px",
        sScrollX: true,
        sScrollXInner: "100%",
        aaSorting: [[5, "desc"]],
        aLengthMenu: [10, 30, 50, 100],
        aoColumns: [{
            mData: "checkbox",
            sTitle: "<label class='pos-rel' title='全选'><input type='checkbox' class='ace'><span class='lbl'></span></label>",
            sWidth: "50px",
            sClass: "center",
            bSortable: false,
            bSearchable: false,
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.html("<label class='pos-rel'><input type='checkbox' class='ace' data-id='{0}'><span class='lbl'></span></label>".format(rowData.id));
            }
        }, {
            mData: "roleName",
            sName: "roleName",
            sTitle: "角色名称",
            sWidth: "200px"
        }, {
            mData: "roleCode",
            sName: "roleCode",
            sTitle: "角色代码",
            sWidth: "150px"
        }, {
            mData: "resourceNames",
            sName: "resourceNames",
            sTitle: "拥有的资源",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);
                var html = "";
                var htmlTpl = "<span class='label label-lg label-primary m-5'>{0}</span>";

                if ($.isNotBlank(rowData.resourceNames)) {
                    var data = rowData.resourceNames.split("|");

                    $.each(data, function (i, e) {
                        html += htmlTpl.format(e);
                    });
                }

                $cell.html(html);
            }
        }, {
            mData: "permissionCodes",
            sName: "permissionCodes",
            sTitle: "拥有的权限",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);
                var html = "";
                var htmlTpl = "<span class='label label-lg label-primary m-5'>{0}</span>";

                if ($.isNotBlank(rowData.permissionCodes)) {
                    var data = rowData.permissionCodes.split("|");

                    $.each(data, function (i, e) {
                        html += htmlTpl.format(e);
                    });
                }

                $cell.html(html);
            }
        }, {
            mData: "createTime",
            sName: "createTime",
            sTitle: "<i class='ace-icon iconfont icon-time bigger-110'></i>时间",
            sWidth: "100px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.html(rowData.createTime.substring(0, 10));
            }
        }, {
            mData: "operator",
            sTitle: "操作",
            sWidth: "100px",
            bSortable: false,
            bSearchable: false,
            sDefaultContent: "<div class='hidden-sm hidden-xs action-buttons'></div>",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.find("div.action-buttons").append("<a class='c-orange' title='修改' href='{0}web/role/update.html?id={1}'><i class='ace-icon iconfont icon-pencil bigger-200'></i></a>".format(globalBasePath, rowData.id));
                $cell.find("div.action-buttons").append("<a class='delete_btn c-red' title='删除' data-id='{0}' data-name='{1}' href='javascript:void(0);'><i class='ace-icon iconfont icon-delete bigger-200'></i></a>".format(rowData.id, rowData.roleName));
            }
        }]
    });

    /**
     *
     * 搜索数据。
     *
     */
    function searchData() {
        // 角色名称
        if ($.isNotBlank($roleName.val()) && ($roleName.val().length > 50)) {
            $.toast({
                top: 5,
                msg: "角色名称的长度不能大于50个字",
                type: "warn",
                close: 3000
            });

            return;
        }

        // 角色代码
        if ($.isNotBlank($roleCode.val()) && ($roleCode.val().length > 50)) {
            $.toast({
                top: 5,
                msg: "角色代码的长度不能大于50个字符",
                type: "warn",
                close: 3000
            });

            return;
        }

        // 开始日期必须小于结束日期
        if ($.isNotBlank($startDate.val()) && $.isNotBlank($endDate.val())) {
            if (Number($startDate.val().replaceAll("-", "")) > Number($endDate.val().replaceAll("-", ""))) {
                $.toast({
                    top: 5,
                    msg: "开始日期应小于结束日期",
                    type: "warn",
                    close: 3000
                });

                return;
            }
        }

        $roleName.val($.trim($roleName.val()));
        $roleCode.val($.trim($roleCode.val()));

        // 搜索开始…
        if ($.isNotNull(roleTable)) {
            roleTable.myAjaxData = {
                endDate: $endDate.val(),
                startDate: $startDate.val(),
                roleName: $roleName.val(),
                roleCode: $roleCode.val()
            };

            // 刷新角色表格（分页重置）
            roleTable.ajax.reload();
        }
    }
});